import axios from 'axios';
import { getDvaApp } from 'umi';
import {
  getEnvURL,
  getObjDecryptData,
  IsSpecialData,
  Cookie,
} from '@/utils/base/utils';
import { Notification, Modal, message } from 'antd';
import { sm2 } from 'sm-crypto';
const { CUSTOM_ENV } = process.env;
const pubkey =
  '039e4e357cf4fd771334f7bca8e152305b83a864c8862302283fd1a39519fdd8a2'; // 加

let tokenAbnormal = false;
// const urlSafe = ['auth', 'system', 'gov', 'auditlog', 'fgw'];
const urlSafe = ['auth', 'system', 'gov', 'fgw'];
const handleUrl = (url = '') => {
  const isHave = urlSafe.find((item) => url.includes(item));
  let str = url;
  if (
    CUSTOM_ENV === 'safe' ||
    CUSTOM_ENV === 'nsafe' ||
    CUSTOM_ENV === 'devsafe'
  ) {
    str = str.replace(isHave, `${isHave}/glzz`);
  }
  return str;
};

const errorCode = {
  401: '认证失败，无法访问系统资源',
  403: '当前操作没有权限',
  404: '访问资源不存在',
  default: '系统未知错误,请反馈给管理员',
};

axios.defaults.headers = {
  'Content-Type': 'application/json;charset=utf-8',
};

// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: '',
  // 超时
  timeout: 50000,
});

// request拦截器
service.interceptors.request.use(
  (config) => {
    const { params, method, data, url } = config;
    config.url = handleUrl(config.url);
    // 是否需要设置 token
    const isToken = (config.headers || {}).Authorization === false;
    if (sessionStorage.getItem('author') && !isToken) {
      config.headers['Authorization'] = sessionStorage.getItem('author'); // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    if (sessionStorage.getItem('tokenUUId')) {
      config.headers['tokenUUId'] = sessionStorage.getItem('tokenUUId');
    }
    if (sessionStorage.getItem('businessCode')) {
      const urlKey = handleUrl(url.split('?')[0].replace('/api', ''));
      const businessCode = sessionStorage.getItem('businessCode');
      const codeVale =
        '04' + sm2.doEncrypt(businessCode + '+' + urlKey, pubkey, 1);
      config.headers['businessCode'] = codeVale;
    }
    if (method == 'post' && data && config.url !== '/api/auth/login') {
      if (CUSTOM_ENV == 'npre' || CUSTOM_ENV == 'nsafe') {
        config.data = data;
      } else {
        config.data = '04' + sm2.doEncrypt(data, pubkey, 1);
      }
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  },
);

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    // 未设置状态码则默认成功状态
    const code = parseInt(res.data.code) || 200;
    // 获取错误信息
    if (code === 401) {
      if (!tokenAbnormal) {
        tokenAbnormal = true;
        Modal.confirm({
          content: res.data.msg,
          cancelText: '取消',
          okText: '确定',
          onOk() {
            getDvaApp()
              ._store.dispatch({
                type: 'login/loginOut',
              })
              .then((res) => {
                const url = getEnvURL();
                if (res.code && parseInt(res.code) == 200) {
                  sessionStorage.clear();
                  Cookie.remove('Authorization');
                  if (!url) {
                    location.href = '/';
                  } else {
                    window.location.href = res.data;
                  }
                }
              });
          },
          onCancel() {
            tokenAbnormal = false;
          },
        });
      }
    } else if (code !== 200) {
      Notification.error({
        message: res.data.msg || res.data.message,
      });
    }
    const resultData = getObjDecryptData(res.data, res.request.responseURL);
    if (IsSpecialData(JSON.stringify(resultData))) {
      message.warn('返回数据存在非法字符');
      return {};
    } else {
      return resultData;
    }
  },
  (error) => {
    let { message: msg } = error;
    if (msg == 'Network Error') {
      msg = '后端接口连接异常';
    } else if (msg.includes('timeout')) {
      msg = '系统接口请求超时';
    } else if (msg.includes('Request failed with status code')) {
      msg = '系统接口' + msg.substr(msg.length - 3) + '异常';
    }
    message.error(msg);
    return { code: null, data: null };
  },
);

export default service;
